#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "../include/vfs.h"

int unmount_vfs(char vfs_name[])
{
	FILE *fp;
	
	FD *fd_store[900];
	
	Tree temp;
	int num_fd=0,i;

	/*if(roots.naryroot==NULL)
		return 4;
*/
	if(strcmp(vfs_name,filesystem_name)!=0)
		return 4;

	fp = fopen(vfs_name,"r+b");

	if(fp==NULL)
	{	
		return 1;
	}
	header = malloc(sizeof(Header));

	fread(header,sizeof(Header),1,fp);

	if(strcmp(header->vfslabel,vfs_name)!=0)
	{
		fclose(fp);
		return 2;
	}
		
		//display(roots.naryroot);

		//displayList(roots.bstRoot);

		temp = roots.naryroot->left;

		//printf("\n TEMP %s",temp->desc->filename);
		
	        unmount(temp,fd_store,&num_fd);

		header->used_FD = num_fd+1;

		for(i=1;i<header->used_FD;i++)
		{
			strcpy(header->fd_list[i].filename,fd_store[i-1]->filename);
			strcpy(header->fd_list[i].path,fd_store[i-1]->path);
			header->fd_list[i].file_type=fd_store[i-1]->file_type;
			header->fd_list[i].file_size=fd_store[i-1]->file_size;
			header->fd_list[i].block_no=fd_store[i-1]->block_no;

		}

	
	rewind(fp);
	fwrite(header,sizeof(Header),1,fp);

	fclose(fp);

	return 0;

}
